"use strict";

module.exports = core;

const path = require("path");
const semver = require("semver");
const colors = require("colors/safe");
const userHome = require("user-home");
const pathExists = require("path-exists").sync;
const commander = require("commander");
const logger = require("./utils/logger");

const constant = require("./const");
const pkg = require("../package.json");
const { refreshUrl } = require('./commands/refresh')

const program = new commander.Command();

async function core() {
  try {
    await prepare();
    registerCommand();
  } catch (e) {
    logger.error(e.message);
    if (program.debug) {
      console.log(e);
    }
  }
}

function registerCommand() {
  program
    .name(Object.keys(pkg.bin)[0])
    .usage("<command> [options]")
    .version(pkg.version)
    .option("-d, --debug", "是否开启调试模式", false)
    .option("-tp, --targetPath <targetPath>", "指定本地调试文件路径", "");

  // program
  //   .command('refresh')
  //   .option('-p, --path', 'title to use before name', false)
  //   .option('-d, --debug', 'display some debugging')
  //   .action((options, command) => {
  //     console.log(options)
  //   });

  program
    .command('refresh')
    .description("刷新CDN")
    .option('-p, --path <paths...>', '刷新URL')
    .option('-d, --dir <dirs...>', '刷新目录')
    .option('--secretId <secretId>', '腾讯云密钥SecretId')
    .option('--secretKey <secretKey>', '腾讯云密钥SecretKey')
    .action(refreshUrl);

  // 开启debug模式
  program.on("option:debug", function () {
    let opts = program.opts();
    if (opts.debug) {
      process.env.LOG_LEVEL = "verbose";
    } else {
      process.env.LOG_LEVEL = "info";
    }
    logger.level = process.env.LOG_LEVEL;
  });

  // 指定targetPath
  program.on("option:targetPath", function () {
    let opts = program.opts();
    process.env.CLI_TARGET_PATH = opts.targetPath;
  });

  // 对未知命令监听
  program.on("command:*", function (obj) {
    const availableCommands = program.commands.map((cmd) => cmd.name());
    console.log(colors.red("未知的命令：" + obj[0]));
    if (availableCommands.length > 0) {
      console.log(colors.red("可用命令：" + availableCommands.join(",")));
    }
  });

  program.parse(process.argv);

  if (program.args && program.args.length < 1) {
    program.outputHelp();
    console.log();
  }
}

async function prepare() {
  checkPkgVersion();
  checkRoot();
  checkUserHome();
  checkEnv();
  // await checkGlobalUpdate();
}

// async function checkGlobalUpdate() {
//   const currentVersion = pkg.version;
//   const npmName = pkg.name;
//   const { getNpmSemverVersion } = require("@facee/get-npm-info");
//   const lastVersion = await getNpmSemverVersion(currentVersion, npmName);
//   if (lastVersion && semver.gt(lastVersion, currentVersion)) {
//     logger.warn(
//       colors.yellow(`请手动更新 ${npmName}，当前版本：${currentVersion}，最新版本：${lastVersion}
//                 更新命令： npm install -g ${npmName}`)
//     );
//   }
// }

function checkEnv() {
  const dotenv = require("dotenv");
  const dotenvPath = path.resolve(userHome, ".env");
  if (pathExists(dotenvPath)) {
    dotenv.config({
      path: dotenvPath,
    });
  }
  createDefaultConfig();
}

function createDefaultConfig() {
  const cliConfig = {
    home: userHome,
  };
  if (process.env.CLI_HOME) {
    cliConfig["cliHome"] = path.join(userHome, process.env.CLI_HOME);
  } else {
    cliConfig["cliHome"] = path.join(userHome, constant.DEFAULT_CLI_HOME);
  }
  process.env.CLI_HOME_PATH = cliConfig.cliHome;
}

function checkUserHome() {
  if (!userHome || !pathExists(userHome)) {
    throw new Error(colors.red("当前登录用户主目录不存在！"));
  }
}

function checkRoot() {
  const rootCheck = require("root-check");
  rootCheck();
}

function checkPkgVersion() {
  logger.info("cli", pkg.version);
}
